#include "unp.h"

#define CONTROL_LEN  (sizeof(struct cmsghdr) + sizeof(struct ucred))

ssize_t read_fd(int fd, void* pbuff);

int main(int argc, char **argv)
{
  int sockfd,n;
  char buf[512] = {'\0'};
  struct sockaddr_un servaddr;
  struct ucred* cred;

  if (argc != 2)
  {
    printf("usage : domaincli <filepath>\n");
    exit(-1);
  }

  memset(&servaddr, 0,sizeof(servaddr));
  sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);

  servaddr.sun_family = AF_LOCAL;
  strcpy(servaddr.sun_path, argv[1]);
  connect(sockfd, (struct sockaddr*) &servaddr, sizeof(servaddr));
  
  while ( (n = read_fd(sockfd,buf)) > 0)
  {
    buf[n] = '\0';
    printf("Receive from server: %s\n",buf);
  }

  return 0;
}

ssize_t read_fd(int fd, void* pbuff)
{
  struct msghdr msg;
  struct iovec  iov[3];
  char buf1[3],buf2[3],buf3[4];
  int n;

  iov[0].iov_base = buf1;
  iov[0].iov_len = 3;
  iov[1].iov_base = buf2;
  iov[1].iov_len = 3;
  iov[2].iov_base = buf3;
  iov[2].iov_len = 3;

  msg.msg_name        = NULL;
  msg.msg_namelen     = 0;
  msg.msg_iov         = iov;
  msg.msg_iovlen      = 3;

  n = readv(fd, iov, 3);

  memcpy(pbuff,buf1,sizeof(buf1)); 
  memcpy(pbuff+sizeof(buf1),buf2,sizeof(buf2));
  memcpy(pbuff+sizeof(buf1) + sizeof(buf2),buf3,sizeof(buf3));
 
  return n;
}
